package com.nervenets.web.config;

import com.nervenets.utils.JodaUtils;
import com.nervenets.web.service.MailService;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.File;
import java.io.PrintWriter;

/**
 * Created by Joe on 2018/2/5.
 */
@Configuration
public class MessageQueueConfiguration {
    @Value("${spring.rabbitmq.listener.simple.prefetch}")
    private int prefetchCount;
    @Value("${spring.rabbitmq.listener.simple.acknowledge-mode}")
    private AcknowledgeMode mode;
    @Resource
    MailService mailService;

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setPrefetchCount(prefetchCount);
        factory.setAcknowledgeMode(mode);
        factory.setErrorHandler(throwable -> {
            try {
                File errorFile = new File(JodaUtils.getTimestamp() + "-err.log");
                if (!errorFile.exists()) errorFile.createNewFile();
                PrintWriter printWriter = new PrintWriter(errorFile);
                throwable.printStackTrace(printWriter);
                printWriter.flush();
                printWriter.close();

                mailService.sendExceptions("消息队列", JodaUtils.timeLongToString(JodaUtils.getTimestamp() * 1000L, "MM-dd HH:mm:ss"), errorFile.getAbsolutePath());
                errorFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return factory;
    }
}
